package com.dhruvtaara.beta.action;

import com.dhruvtaara.beta.model.persistance.Datastore;
import com.dhruvtaara.beta.toolset.DefaultEncryption;
import com.dhruvtaara.beta.toolset.PasswordGenerator;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class ChangePasswordAction {

	/**
	 * 
	 * @param oldpassword
	 * @param newpassword
	 * @return
	 */
	public boolean change(String emailId, String oldpassword, String newpassword) {
		DatastoreService datastore = Datastore.get();
		Query query = new Query("User");
		query.addFilter("emailAddress", FilterOperator.EQUAL, emailId);
		query.addFilter("password", FilterOperator.EQUAL,
				DefaultEncryption.encrypt(oldpassword));

		Entity user = datastore.prepare(query).asSingleEntity();
		if (user == null)
			return false;

		user.setProperty("password", newpassword);

		datastore.put(user);
		return true;
	}

	/**
	 * 
	 * @param emailId
	 * @return
	 */
	public boolean reset(String emailId) {
		DatastoreService datastore = Datastore.get();
		Query query = new Query("User");
		query.addFilter("emailAddress", FilterOperator.EQUAL, emailId);			

		Entity user = datastore.prepare(query).asSingleEntity();
		if (user == null)
			return false;

		user.setProperty("password", PasswordGenerator.generate());

		datastore.put(user);
		
		return true;
	}
}
